package sol.leetcode;

import java.util.*;

/**
 * Peeking Iterator
 */
public class Issue284 {
    public static void main(String[] args) {

        List<Integer> list = new ArrayList<Integer>() {
            {
                add(1);
                add(2);
                add(3);
            }
        };

        Iterator<Integer> iterator = list.iterator();
        PeekingIterator peekingIterator = new PeekingIterator(iterator);

        while (peekingIterator.hasNext()) {
            int peek = peekingIterator.peek();
            int next = peekingIterator.next();
            System.out.println("peek=" + peek + ", next=" + next);
        }
    }
}

class PeekingIterator implements Iterator<Integer> {

    Iterator<Integer> iterator;
    Integer nextVal;//使用一个字段存储下一个要访问的值

    public PeekingIterator(Iterator<Integer> iterator) {
        this.iterator = iterator;
        nextVal = iterator.next();
    }

    public Integer peek() {
        return nextVal;
    }

    @Override
    public Integer next() {
        int res = nextVal;
        if (iterator.hasNext())
            nextVal = iterator.next();
        else
            nextVal = null;
        return res;
    }

    @Override
    public boolean hasNext() {
        return nextVal != null;
    }

    @Override
    public void remove() {

    }
}
